package com.holystone.orca.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 类对比工具
 * Copyright (c) 2015, HOLYSTONE Technologies, Inc.
 * All right reserved.
 * @desc:
 * @author:李海宁
 * @date:2016年11月21日 下午2:46:43
 */
public class ClassCompare {
	/**
	 * 对比两个对象的属性值对否相同
	 * @author: 李海宁
	 * @date: 2016年11月21日 下午2:43:45
	 * @param oldBean
	 * @param newBean
	 * @return
	 */
	public static<T> boolean compareFieldValue(T oldBean, T newBean) {
		try {
			Class<? extends Object> clazz = oldBean.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				if ("serialVersionUID".equals(field.getName())) {
					continue;
				}
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);
				Method getMethod = pd.getReadMethod();
				Object o1 = getMethod.invoke(oldBean);
				Object o2 = getMethod.invoke(newBean);
				if (o1 == null && o2 == null) {
					continue;
				}else if(o1 != null && o2 != null){
					if (!o1.toString().equals(o2.toString())) {
						return false;
					}
				}else{
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	public static void main(String[] args) {
		Student a = new Student();
		a.setAge(20);
		a.setName("小1明");
		a.setSex('男');
		Student b = new Student();
		b.setAge(20);
		b.setName("小明");
		b.setSex('男');
		System.out.println(compareFieldValue(a, b));
	}
	
}

class Student {
	String name;
	int age;
	char sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public char getSex() {
		return sex;
	}
	public void setSex(char sex) {
		this.sex = sex;
	}
	
}